package model;

import java.awt.geom.Point2D;
import java.util.*;

public class Polynomial {
    public ArrayList<Point2D.Double> terms;
    
    public Polynomial(String poly){
    	terms = new ArrayList<Point2D.Double>();
    	Scanner s = new Scanner(poly);
    	
    	int power;
    	double coeff;
    	
    	while(s.hasNext()){
    		coeff = s.nextDouble();
			power = s.nextInt();
			addTerm(coeff, power);
		}
    	
    	s.close();
    }
    
    public void addTerm(double coeff, int power) {
        terms.add(new Point2D.Double(coeff, power)); 
        Collections.sort(terms, new Point2DComparator());
    }
    
    public double evaluate(double x) {
        double eval = 0;
        for (Point2D.Double poly : terms)
            eval += Math.pow(x, poly.y) * poly.x;
        return eval;
    }
}

class Point2DComparator implements Comparator<Point2D.Double> {
    public int compare(Point2D.Double d1, Point2D.Double d2) {
        return (int)d1.y - (int)d2.y;
    }
}